<template>
  <div class="register-container">
    <!-- 背景装饰 -->
    <div class="hotel-bg">
      <div class="hotel-lobby"></div>
    </div>
    
    <el-card class="register-card">
      <div class="register-header">
        <h1>酒店管理系统注册</h1>
        <p>加入我们，开启酒店管理之旅</p>
      </div>
      
      <el-form 
        ref="registerForm" 
        :model="formData" 
        :rules="formRules" 
        label-width="100px"
        class="register-form"
      >
        <!-- 用户名输入框 -->
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="formData.username" 
            placeholder="请输入用户名"
            @blur="checkUsername"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
          <div v-if="usernameStatus === 'checking'" class="status-text">
            <el-icon class="is-loading"><Loading /></el-icon>
            正在检查用户名...
          </div>
          <div v-if="usernameStatus === 'exists'" class="status-text error">
            <el-icon><CircleCloseFilled /></el-icon>
            该用户名已被使用
          </div>
          <div v-if="usernameStatus === 'available'" class="status-text success">
            <el-icon><CircleCheckFilled /></el-icon>
            用户名可用
          </div>
        </el-form-item>
        
        <!-- 密码输入框 -->
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="formData.password" 
            type="password" 
            placeholder="至少6位密码"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="formData.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="formData.phone" 
            placeholder="请输入手机号(可选)"
          >
            <template #prefix>
              <el-icon><Iphone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="formData.email" 
            placeholder="请输入邮箱(可选)"
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <!-- 注册按钮 -->
        <el-form-item>
          <el-button 
            type="primary" 
            class="register-btn"
            @click="submitForm"
            :loading="isSubmitting"
          >
            立即注册
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="register-footer">
        <p>已有账号? <router-link to="/login">立即登录</router-link></p>
      </div>
    </el-card>
  </div>
</template>

<script>
import { listUser, addUser } from '@/api/User.js';

export default {
  name: 'RegisterPage',
  data() {
    // 在闭包中保存this引用，用于验证器
    const self = this;
    
    // 确认密码验证器
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== self.formData.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };
    
    return {
      // 表单数据
      formData: {
        username: '',
        password: '',
        confirmPassword: '',
        phone: '',
        email: ''
      },
      
      // 用户名检查状态
      usernameStatus: null, // null, 'checking', 'exists', 'available'
      
      // 提交状态
      isSubmitting: false,
      
      // 表单验证规则
      formRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        phone: [
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        email: [
          {
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: '请输入正确的邮箱地址',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  methods: {
    // 检查用户名是否可用
    async checkUsername() {
      if (!this.formData.username) return;
      
      this.usernameStatus = 'checking';
      try {
        const response = await listUser({ username: this.formData.username });
        const exists = response.rows.some(user => user.username === this.formData.username);
        
        this.usernameStatus = exists ? 'exists' : 'available';
      } catch (error) {
        console.error('检查用户名失败:', error);
        this.usernameStatus = null;
        this.$message.error('用户名检查失败，请稍后再试');
      }
    },
    
    // 提交注册表单
    async submitForm() {
      try {
        // 验证表单
        const valid = await this.$refs.registerForm.validate();
        if (!valid) return;
        
        // 再次检查用户名是否可用
        if (this.usernameStatus !== 'available') {
          this.$message.warning('请检查用户名是否可用');
          return;
        }
        
        this.isSubmitting = true;
        
        // 构建注册数据
        const registerData = {
          username: this.formData.username,
          password: this.formData.password,
          phone: this.formData.phone,
          email: this.formData.email,
          // 默认状态正常，非管理员
          status: 1,
          is_admin: 0
        };
        
        // 调用注册接口
        await addUser(registerData);
        
        this.$message.success('注册成功！');
        console.log('注册成功');
        
        // 重置表单
        this.$refs.registerForm.resetFields();
        this.usernameStatus = null;
        
        // 注册成功后跳转到登录页面
        this.$router.push('/login');
      } catch (error) {
        console.error('注册失败:', error);
        let errorMsg = '注册失败，请重试';
        if (error.response && error.response.data) {
          errorMsg = error.response.data.message || errorMsg;
        }
        this.$message.error(errorMsg);
      } finally {
        this.isSubmitting = false;
      }
    }
  }
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.hotel-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect fill="none" stroke="%23d1e0f0" stroke-width="0.5" x="0" y="0" width="100" height="100"/></svg>');
  background-size: 20px 20px;
  opacity: 0.6;
  z-index: 0;
}

.hotel-lobby {
  position: absolute;
  bottom: 0;
  right: 5%;
  width: 300px;
  height: 200px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 60"><rect fill="%23d1dbeb" x="10" y="30" width="80" height="30" rx="2"/><rect fill="%23a0b3d1" x="15" y="20" width="10" height="10"/><rect fill="%23a0b3d1" x="35" y="20" width="10" height="10"/><rect fill="%23a0b3d1" x="55" y="20" width="10" height="10"/><rect fill="%23a0b3d1" x="75" y="20" width="10" height="10"/><rect fill="%23c8d5ea" x="0" y="50" width="100" height="10"/></svg>');
  background-size: contain;
  background-repeat: no-repeat;
  opacity: 0.7;
}

.register-card {
  width: 100%;
  max-width: 500px;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
  background: rgba(255, 255, 255, 0.95);
  border: none;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
  padding-top: 20px;
}

.register-header h1 {
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 24px;
}

.register-header p {
  color: #7f8c8d;
  font-size: 14px;
}

.register-form {
  padding: 0 20px;
}

.status-text {
  font-size: 12px;
  margin-top: 5px;
  display: flex;
  align-items: center;
}

.status-text .el-icon {
  margin-right: 5px;
}

.status-text.checking {
  color: #409eff;
}

.status-text.error {
  color: #f56c6c;
}

.status-text.success {
  color: #67c23a;
}

.register-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  background: linear-gradient(135deg, #409eff 0%, #2c6fd1 100%);
  border: none;
  border-radius: 8px;
  margin-top: 10px;
  transition: all 0.3s;
}

.register-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.register-footer {
  text-align: center;
  padding: 20px 0;
  font-size: 14px;
  color: #7f8c8d;
  border-top: 1px solid #eee;
  margin-top: 10px;
}

.register-footer a {
  color: #409eff;
  text-decoration: none;
}

.register-footer a:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .register-card {
    margin: 20px;
    width: calc(100% - 40px);
  }
  
  .hotel-lobby {
    display: none;
  }
}
</style>